<template>
  <a-modal v-model="visible" destroyOnClose :maskClosable="false" centered :width="1100" :afterClose="afterClose">
    <template slot="title">
      <div class="disFlxAC">
        <div class="_mr-20">{{ modalTitle }}</div>
        <a-alert
          v-if="activityInfo.activityType === 'other_join' && activityInfo.enrollVerify === 1"
          message="当前活动已开启报名审核，本次新增报名需要活动发布方审核通过后才报名成功。"
          banner
        />
      </div>
    </template>

    <a-tabs v-model="currentKey">
      <a-tab-pane :key="1" tab="报名信息">
        <div class="disFlx flexAStart">
          <!-- :personTel="rowData.personTel" -->

          <div style="flex: 1;" ref="leftDiv">
            <a-form-model-item v-if="modalType === 'add'" label="报名类型" :labelCol="{ span: 5 }">
              <a-select
                v-model="activityTicketId"
                placeholder="请选择报名类型"
                allowClear
                style="width: 59%"
                :disabled="modalType === 'audit' || modalType === 'check'"
              >
                <a-select-option v-for="item in ticketList" :key="item.value" :value="item.id">
                  {{ item.ticketName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <Form :item="itemList" :disabled="modalType === 'audit' || modalType === 'check'" />
          </div>
          <div v-if="modalType === 'audit'">
            <RegistrationInfo :registerId="rowData.id" :leftDivHeight="leftDivHeight"></RegistrationInfo>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane
        v-if="rowData.signStatus === signStatusEnum.END && rowData.signType === signTypeEnum.REPLACE"
        :key="2"
        tab="代签到人信息"
        force-render
      >
        <a-form-model ref="form" :model="formSign" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
          <a-form-model-item label="代签人">
            <a-input v-model="formSign.replaceSignPersonName" />
          </a-form-model-item>
          <a-form-model-item label="手机号码">
            <a-input v-model="formSign.replaceSignPersonPhone" />
          </a-form-model-item>
          <a-form-model-item label="单位名称">
            <a-input v-model="formSign.replaceSignCompanyName" />
          </a-form-model-item>
          <a-form-model-item label="单位职务">
            <a-input v-model="formSign.replaceSignCompanyPosition" />
          </a-form-model-item>
        </a-form-model>
      </a-tab-pane>
    </a-tabs>

    <template #footer>
      <div v-if="modalType === 'audit'">
        <a-button @click="handleApproval(2)">驳回</a-button>
        <a-button type="primary" @click="handleApproval(3)">通过</a-button>
      </div>
      <div v-else-if="modalType === 'check'">
        <a-button type="primary" @click="closeModal">确定</a-button>
      </div>
      <div v-else>
        <a-button @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="submit">确定</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import Form from '@/components/Form'
import { convertFieldValue } from '@/api/member/member'

import { activityRegisterFormItem } from '@/api/activity/register'
import {
  addActivityRegister,
  updateActivityRegister,
  activityRegisterVerify,
  getTicketList
} from '@/api/activity/activity'
import { replaceSign } from '@/api/activity/enroll'
import { signStatusEnum, signTypeEnum } from '@/enums/activity'
import moment from 'moment'
import { debounce } from '@/utils/common'
import { cloneDeep, isObject } from 'lodash-es'
import registerBatchVerify from '@/views/activity/mixins/registerBatchVerify'
import RegistrationInfo from './RegistrationInfo.vue'
export default {
  mixins: [registerBatchVerify],
  components: {
    RegistrationInfo,
    Form
  },
  props: {
    // 活动ID
    activityId: {
      type: Number | String
    },
    activityInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      itemList: [],
      answerList: [],
      ticketList: [],
      activityTicketId: undefined,
      rowData: {},
      currentKey: 1,
      signStatusEnum,
      signTypeEnum,
      formSign: {
        replaceSignCompanyName: undefined,
        replaceSignCompanyPosition: undefined,
        replaceSignPersonName: undefined,
        replaceSignPersonPhone: undefined
      },
      modalType: 'add', // add 新增 edit 编辑 audit 审核 check 查看,
      observer: null,
      leftDivHeight: 0
    }
  },
  beforeDestroy() {
    this.disconnectObserver()
  },
  computed: {
    modalTitle() {
      if (this.modalType === 'audit') return '审核报名用户'
      if (this.modalType === 'check') return '查看报名用户'
      if (this.modalType === 'edit') return '编辑报名用户'
      return '新增报名用户'
    }
  },
  methods: {
    initObserver() {
      this.$nextTick(() => {
        if (this.$refs.leftDiv) {
          this.observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
              if (mutation.type === 'childList' || mutation.type === 'attributes') {
                this.checkScrollHeight()
              }
            })
          })
          if (this.$refs.leftDiv instanceof HTMLElement) {
            this.observer.observe(this.$refs.leftDiv, { childList: true, attributes: true, subtree: true })
          }
        }
      })
    },
    checkScrollHeight() {
      this.leftDivHeight = this.$refs.leftDiv.scrollHeight
    },
    disconnectObserver() {
      if (this.observer) {
        this.observer.disconnect()
      }
    },
    openModal(rowData, type) {
      this.rowData = cloneDeep(rowData) // 报名人信息
      this.modalType = type
      this.currentKey = 1
      this.activityTicketId = rowData.activityTicketId
      this.$nextTick(() => {
        Object.keys(this.formSign).forEach(k => {
          this.formSign[k] = this.rowData[k]
        })
      })
      this.visible = true
      this.getActivityRegisterFormItem()
      this.handelTicketListDownList()
      this.initObserver()
    },
    handelTicketListDownList() {
      return getTicketList(this.activityId).then(res => {
        if (res.code === 0) {
          this.ticketList = res.data || []
          this.activityTicketId = res.data[0].id
        }
      })
    },
    closeModal() {
      this.visible = false
    },
    async getActivityRegisterFormItem() {
      let res = await activityRegisterFormItem(this.activityId, this.rowData.id)
      let itemList = res.data.activityFormItemMap[0] || []
      let answerList = res.data.activityFormUserAnswerList || []

      this.itemList = itemList.map((item, index) => {
        let answerItem = answerList.find(f => f.formItemId === item.id)

        let text = convertFieldValue(answerItem, item)

        console.log(item)

        return {
          ...item,
          isRequired: index === 0 ? 1 : 0,
          content: text,
          extra: item.id == -1 ? '请确认手机号码与报名用户的微信绑定号码一致，否则会无法签到' : ''
        }
      })
      this.answerList = res.data.activityFormUserAnswerList || []
      this.activityTicketId = res.data.activityTicketId
    },
    afterClose() {},
    async submit() {
      try {
        if (this.currentKey === 2) {
          this.confirmLoading = true
          await replaceSign({
            id: this.rowData.id,
            signType: signTypeEnum.REPLACE,
            ...this.formSign
          })
          this.$emit('success')
          this.$message.success('编辑成功')
        } else {
          let nameItem = this.itemList[0] || {}
          if (!nameItem.content) return this.$message.warning('请输入姓名')
          const answerList = []
          for (let index = 0; index < this.itemList.length; index++) {
            const item = this.itemList[index]
            let answerItem = this.answerList.find(f => f.formItemId === item.id) || {}
            let content = []
            if (Array.isArray(item.content)) {
              content = item.content.map(text => (isObject(text) ? JSON.stringify(text) : text))
              // if (item.itemType === 'UploadFile' || item.itemType === 'ApplyTable')
              //   content = content.map(m => JSON.stringify(m))
            } else if (item.content) {
              if (item.itemType === 'TimePicker') {
                content = [moment(item.content).format('HH:mm')]
              } else {
                content = [item.content.toString()]
              }
            } else if (item.content === 0) {
              content = [item.content]
            }

            if (item.itemType === 'Attachment') {
              continue
            }
            answerList.push({
              formItemId: item.id,
              id: answerItem.id,
              content
            })
          }
          let activityFormItem = {
            answerList
          }

          this.confirmLoading = true
          if (this.rowData.id) {
            const { data } = await updateActivityRegister({
              id: this.rowData.id,
              activityTicketId: this.activityTicketId,
              activityFormItem: {
                ...activityFormItem
              }
            })
            this.$message.success('编辑成功')
            this.$emit('success')
          } else {
            const { data } = await addActivityRegister({
              activityId: this.activityId,
              activityTicketId: this.activityTicketId,
              activityFormItem: {
                ...activityFormItem
              }
            })
            this.$message.success('新增成功')
            this.$emit('success', data)
          }
        }
        this.closeModal()
        this.confirmLoading = false
      } catch (error) {
        this.confirmLoading = false
        console.log(error)
      }
    },
    handleApproval(status) {
      debounce(async () => {
        this.batchVerify({
          title: '批量报名审核',
          okText: '确定驳回',
          activityUnionId: this.activityId,
          status,
          cancelText: '取消',
          ids: [this.rowData.id],
          callback: data => {
            this.$emit('success', data)
            if (status === 3) {
              // 审核通过
              this.$emit('openSetLabel', this.rowData)
            }
            this.closeModal()
          }
        })
      })
    }
  }
}
</script>

<style></style>
